<template>
  <div class="myhome">
    <!-- 用户信息框 -->
      <!-- 用户操作按钮 -->
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <section class="user-actions">
      <button @click="goToMySongs" class="btn btn-outline-primary">我的歌曲</button>
      <button @click="goToNote" class="btn btn-outline-secondary">我的笔记</button>
      <button @click="goToMyInstruments" class="btn btn-outline-success">我的乐器</button>
      <button @click="goToMyKnowledge" class="btn btn-outline-info">我的知识</button>
      <button @click="goToMyScores" class="btn btn-outline-warning">我的乐谱</button>
      <button @click="goToCultureBack" class="btn btn-outline-danger">我的文化背景</button>
    </section>
    <section class="user-info">

      <div class="user-profile">
        <img
          v-if="editForm.profile_picture"
          :src="'http://localhost:8080/images/upload/' + editForm.profile_picture"
          alt="头像"
          class="avatar"
        />
        <br><br>
        <div class="user-details">
          <h2 class="user-name">{{ userName }}</h2>
          <p class="user-follow-count">关注数：{{ followerCount }}</p>
          <p class="user-follower-count">粉丝数：{{ followingCount }}</p>
          <p class="user-biography">{{ biography }}</p>
          <el-button @click="openEditModal" type="primary" class="edit-btn">编辑资料</el-button>
        </div>
            <!-- 中国风按钮组 -->
    <section class="chinese-style-actions">

      <el-button @click="goToMyFocus" class="action-btn">关注列表</el-button>
      <el-button @click="goToMyFan" class="action-btn">粉丝列表</el-button>

    </section>
      </div>
    </section>

    <!-- 饼状图部分 -->
    <section class="charts-container">
      <div class="chart">
        <h3 class="chart-title">收藏歌曲类别</h3>
        <div ref="chart1" class="chart-area"></div>
      </div>
    </section>

    <!-- 编辑个人信息的弹窗 -->
    <el-dialog
      :title="'编辑个人信息'"
      v-model="isEditModalVisible"
      width="50%"
      @close="resetEditForm"
      class="edit-modal"
    >
      <el-form ref="editForm" :model="editForm" label-width="120px" class="form">
        <el-form-item label="用户名">
          <el-input v-model="editForm.user_name" placeholder="输入用户名" class="input"></el-input>
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input
            type="textarea"
            v-model="editForm.biography"
            placeholder="简短介绍一下自己"
            class="input"
          ></el-input>
        </el-form-item>
        <el-form-item label="音乐标签">
          <el-select v-model="editForm.music_label" placeholder="请选择音乐标签" class="input">
            <el-option label="传统音乐" value="传统音乐"></el-option>
            <el-option label="新国风流行" value="新国风流行"></el-option>
            <el-option label="戏曲融合" value="戏曲融合"></el-option>
            <el-option label="主题文化" value="主题文化"></el-option>
            <el-option label="地域特色" value="地域特色"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.user_sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
            <el-radio label="其他"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            type="date"
            placeholder="选择生日"
            v-model="editForm.user_birthday"
            class="input"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/v1/user/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="editForm.profile_picture"
              :src="'http://localhost:8080/images/upload/' + editForm.profile_picture"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="国家/地区">
          <el-input
            v-model="editForm.country_region"
            placeholder="请输入所在国家或地区"
            class="input"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="closeEditModal" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="saveEdit" class="save-btn">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

        <!-- AI 作曲功能 -->
        <section class="ai-compose-section">
      <h2>AI 作曲</h2>
      <el-button @click="goToAiCompose" class="chinese-style-btn">开始作曲</el-button>
      
      <!-- 弹窗 -->
      <el-dialog
        title="AI 作曲"
        v-model="isAiComposeModalVisible"
        width="60%"
        @close="resetAiComposeForm"
      >
        <div class="ai-compose-container">
          <!-- 作曲参数输入表单 -->
          <el-form :model="aiComposeForm" label-width="100px" class="ai-compose-form">
            <el-form-item label="风格">
              <el-select v-model="aiComposeForm.style" placeholder="选择作曲风格">
                <el-option label="传统音乐" value="传统音乐"></el-option>
                <el-option label="新国风" value="新国风"></el-option>
                <el-option label="戏曲融合" value="戏曲融合"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时长 (秒)">
              <el-input v-model="aiComposeForm.duration" type="number" placeholder="输入时长"></el-input>
            </el-form-item>
            <el-form-item label="节奏 (BPM)">
              <el-input v-model="aiComposeForm.tempo" type="number" placeholder="输入节奏"></el-input>
            </el-form-item>
          </el-form>

          <!-- 按钮 -->
          <div class="ai-compose-actions">
            <el-button type="primary" @click="generateAiComposition">生成音乐</el-button>
          </div>

          <!-- 作曲结果 -->
          <div v-if="aiCompositionUrl" class="composition-result">
            <h3>生成结果</h3>
            <audio controls :src="aiCompositionUrl"></audio>
          </div>
        </div>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import router from "../router/index.js";

export default {
  data() {
    return {
      userId: this.$route.query.user_id,
      userName: "",
      followerCount: 0, // 粉丝数初始化
      followingCount: 0 ,// 关注数初始化
      userSex:"",
      userBirthday:"",
      countryRegion:"",
      userStatus:"",
      musicTypeCounts: {}, // 存储歌曲种类数量
      followerCount:"",
      followingCount:"",
      biography: "",
      editForm: {
        user_name: "",
        biography: "",
        music_label: "",
        user_sex: "",
        user_birthday: "",
        profile_picture: "",
        country_region: "",
      },
      isEditModalVisible: false,
      charts: {
        chart1: null,
      },
    };
  },
  mounted() {
    this.userId = sessionStorage.getItem("user_id") || localStorage.getItem("user_id");
    this.getUserInfo();
    this.fetchMusicTypeCounts();
    this.fetchFollowerCount();
    this.fetchFollowingCount();
    this.initCharts();
  },
  methods: {
    async getUserInfo() {
      try {
        const response = await axios.get(`http://localhost:8080/v1/user/${this.userId}`);
        const userData = response.data;
        this.userName = userData.user_name;
        this.userSex = userData.user_sex;
        this.userBirthday = userData.user_birthday;
        this.countryRegion = userData.country_region;
        this.userStatus = userData.user_status;

        this.biography = userData.biography;
        this.editForm = { ...userData };
      } catch (error) {
        console.error("获取用户信息失败", error);
        ElMessage.error("获取用户信息失败");
      }
    },
    openEditModal() {
      this.isEditModalVisible = true;
    },
    closeEditModal() {
      this.isEditModalVisible = false;
    },
    async fetchFollowerCount() {
     try {
       const response = await axios.get(`http://localhost:8080/user/${this.userId}/followers/count`); 
       this.followerCount = response.data;
     } catch (error) {
       console.error("获取粉丝数失败", error);
       ElMessage.error("获取粉丝数失败");
     }
   },
    async fetchFollowingCount() {
     try {
       const response = await axios.get(`http://localhost:8080/user/${this.userId}/following/count`); 
       this.followingCount = response.data;
     } catch (error) {
       console.error("获取关注数失败", error);
       ElMessage.error("获取关注数失败");
     }
   },
   fetchMusicTypeCounts() {
  const user_id = this.userId;
  axios.get(`http://localhost:8080/mc/types/count`, { params: { user_id: user_id } })
    .then(response => {
      this.musicTypeCounts = response.data;
      this.initCharts();
    })
    .catch(error => {
      console.error("获取歌曲种类数量失败", error);
      ElMessage.error("获取歌曲种类数量失败，请检查网络连接或联系管理员。");
    });
},
    async saveEdit() {
      try {
        const response = await axios.put(`http://localhost:8080/v1/update/${this.userId}`,  this.editForm);
        if (response.data && response.data === 1) {
          ElMessage.success("信息更新成功");
          this.getUserInfo();
          this.closeEditModal();
        } else {
          ElMessage.error("信息更新失败，请稍后再试");
        }
      } catch (error) {
        ElMessage.error("保存失败，请检查网络连接");
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        ElMessage.error('请选择图片文件!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    handleAvatarSuccess(response) {
      console.log(response);
      this.editForm.profile_picture = response;
    },
    goToNote() {
      this.$router.push({ name: 'MyNote', params: { user_id: Number(this.userId) } });
    },
    goToEmail() {
      this.$router.push({ name: 'Email', params: { user_id: Number(this.userId) } });
    },
    goToMyFocus() {
      this.$router.push({ name: 'MyFocus', params: { user_id: Number(this.userId) } });
    },
    goToMyFan() {
      this.$router.push({ name: 'MyFan', params: { user_id: Number(this.userId) } });
    },
    goToMySongs() {
     this.$router.push({ name: 'MusicCollection', params: { user_id: this.userId } });
   },
    goToMyScores() {
     this.$router.push({ name: 'MyScores', params: { user_id: this.userId } });
   },
   goToCultureBack(){
    this.$router.push({ name: 'MyCultureBack', params: { user_id: this.userId } });
   } ,   
   goToMyInstruments() {
     this.$router.push({ name: 'MyInstruments', params: { user_id: this.userId } });
   },
    goToMyKnowledge() {
     this.$router.push({ name: 'MyKnowledge', params: { user_id: this.userId } });
   },
    goToMyNotes() {
     this.$router.push({ name: 'MyNotes', params: { user_id: this.userId } });
   },
   goToAiCompose() {
    window.location.href = 'http://cf69ab7.r8.cpolar.top';
  },
   initCharts() {
  if (!this.$refs.chart1) return;
  this.charts.chart1 = echarts.init(this.$refs.chart1);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      top: 'bottom',
    },
    series: [
      {
        name: '歌曲类别',
        type: 'pie',
        radius: '55%',
        data: Object.keys(this.musicTypeCounts).map(key => ({
          value: this.musicTypeCounts[key],
          name: key,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  this.charts.chart1.setOption(option);
},
  },
};
</script>

<style scoped>
/* 古香古色样式 */
.myhome {
  max-width: 1200px;
  margin: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 添加垂直居中 */
  justify-content: center; /* 添加水平居中 */
  gap: 30px;
  background-image: url('/path-to-your-background-image.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}

.user-info {
  padding: 20px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 确保子元素垂直居中 */
  justify-content: center; /* 确保子元素水平居中 */
  gap: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  background-image: url('http://localhost:8080/images/upload/111.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  width: 100%; /* 确保元素占满整个容器宽度 */
  height: 100%; /* 确保元素占满整个容器高度 */
}

/* 中国风按钮组样式 */
.chinese-style-actions {
  display: flex;
  justify-content: center; /* 确保按钮组水平居中 */
  gap: 15px;
  margin-top: 20px;
}

/* 中国风按钮样式 */
.chinese-style-btn {
  background-color: #f5deb3; /* 米色背景 */
  border: 1px solid #ae8033; /* 棕色边框 */
  color: #663d00; /* 深棕色文字 */
  padding: 10px 20px;
  border-radius: 5px;
  font-family: 'KaiTi', 'STKaiti', serif;
  transition: background-color 0.3s, transform 0.3s;
}

.chinese-style-btn:hover {
  background-color: #e0c9a7; /* 深米色 */
  transform: translateY(-3px); /* 轻微下移 */
}

/* 头像样式 */
.avatar {
  width: 100px; /* 放大头像宽度 */
  height: 100px; /* 放大头像高度 */
  border-radius: 50%;
  border: 5px solid #d9c5a1;
  margin-left: 70px; /* 将头像向右移动 */
  margin-right: 10px; /* 根据需要调整这个值 */
}

.user-details {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  flex-direction: column; /* 子元素垂直排列 */
  gap: 10px; /* 子元素之间的间距 */
}

.edit-btn {
  background-color: #ae8033;
  color: #fff;
  border-radius: 5px;
  padding: 5px 10px;
  font-family: 'KaiTi', 'STKaiti', serif;
}

.user-actions {
  display: flex;
  justify-content: center; /* 确保动作按钮水平居中 */
  gap: 20px;
}

.action-btn {
  background-color: #f5deb3;
  border: 0px solid #ae8033;
  color: #663d00;
  font-family: 'KaiTi', 'STKaiti', serif;
}

.charts-container {
  padding: 20px;
  font-family: 'KaiTi';
  display: flex;
  justify-content: center; /* 确保图表容器水平居中 */
}

.chart {
  text-align: center;
}

.chart-area {
  height: 400px; /* 增大饼图高度 */
  width: 400px; /* 增大饼图宽度 */
}

.edit-modal .el-dialog {
  background-color: #f5deb3;
  border: 1px solid #ae8033;
  border-radius: 5px;
  font-family: 'KaiTi', 'STKaiti', serif;
}

.edit-modal .form {
  font-family: 'KaiTi', 'STKaiti', serif;
}

.el-button {
  font-family: 'KaiTi', 'STKaiti', serif;
}
</style>